package own.stu.jobgib.playown.netty.teston.queue;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import own.stu.jobgib.playown.netty.teston.HttpRequestWrapper;
import own.stu.jobgib.playown.netty.teston.RemotingHelper;
import io.netty.handler.codec.http.*;
import io.netty.util.ReferenceCountUtil;
import lombok.extern.slf4j.Slf4j;
import org.asynchttpclient.netty.util.ByteBufUtils;

import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;

/**
 * <B>主类名称：</B>NettyCoreProcessor<BR>
 * <B>概要说明：</B>核心流程的主执行逻辑<BR>
 *
 * @author JiFeng
 * @since 2021年12月5日 下午9:51:34
 */
@Slf4j
public class NettyCoreProcessor implements NettyProcessor<own.stu.jobgib.playown.netty.teston.HttpRequestWrapper> {

    public static void main(String[] args) throws Exception {
        ByteBuf body = Unpooled.wrappedBuffer("Http message too!".getBytes("UTF-8"));
        String s = ByteBufUtils.byteBuf2String(Charset.defaultCharset(), body);
        System.out.println(s);
    }

    @Override
    public void process(own.stu.jobgib.playown.netty.teston.HttpRequestWrapper event) throws Exception {
        FullHttpRequest request = event.getFullHttpRequest();

        if (request.content() != null) {
            String remoteAddr = RemotingHelper.parseChannelRemoteAddr(event.getCtx().channel());
            log.info("get from client remoteAddr : {}, content : {}",
                    remoteAddr,
                    ByteBufUtils.byteBuf2String(Charset.defaultCharset(), request.content()));
        }

        ChannelHandlerContext ctx = event.getCtx();
        ByteBuf body = Unpooled.wrappedBuffer("Http message too!".getBytes("UTF-8"));
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, body);
        // 注意要写内容长度，不然客户端解码会有问题
        response.headers().set(HttpHeaderNames.CONTENT_LENGTH, body.readableBytes());
        TimeUnit.MILLISECONDS.sleep(50);
        ctx.writeAndFlush(response).sync();
        System.out.println("Http Server send response succeed .. ");
    }


    /**
     * <B>方法名称：</B>doWriteAndRelease<BR>
     * <B>概要说明：</B>写回响应信息并释放资源<BR>
     *
     * @param ctx
     * @param request
     * @param response
     * @author JiFeng
     * @since 2021年12月20日 下午6:12:10
     */
    private void doWriteAndRelease(ChannelHandlerContext ctx, FullHttpRequest request, FullHttpResponse response) {
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
        boolean release = ReferenceCountUtil.release(request);
        if (!release) {
            log.warn("#NettyCoreProcessor# doWriteAndRelease release fail 释放资源失败， request:{}, release:{}",
                    request.uri(),
                    release);
        }
    }

    @Override
    public void start() {
        // TODO Auto-generated method stub

    }

    @Override
    public void shutdown() {
        // TODO Auto-generated method stub

    }

}
